package com.jyw.business.obstacles.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.jyw.business.obstacles.domain.ObsOrderMake;
import com.jyw.business.obstacles.domain.vo.web.RepairRemindCountVO;
import com.jyw.business.obstacles.domain.vo.web.ServerDeskWebSocketVO;
import com.jyw.business.obstacles.enums.EvaluateResultEnum;
import com.jyw.business.obstacles.mapper.ObsOrderFaultMapper;
import com.jyw.business.obstacles.service.IObsOrderMakeService;
import com.jyw.business.obstacles.service.IObsOrderMessageService;
import com.jyw.business.obstacles.utils.WebSocketUtils;
import com.jyw.common.constant.CacheConstants;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.utils.LocalTimeUtil;
import com.jyw.system.domain.vo.SysOrderReminderConfigVo;
import com.jyw.system.enums.MessageTypeEnum;
import com.jyw.system.service.ISysMessageService;
import com.jyw.system.service.ISysOrderReminderConfigService;
import com.jyw.system.service.ISysUserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.jyw.business.obstacles.enums.WebSocketCodeEnum.SERVICE_MESSAGE;

/**
 * @author Created by ZhangCheng on 2024/02/21
 */
@Service
@Slf4j
public class ObsOrderMessageServiceImpl implements IObsOrderMessageService {

    @Resource
    private RedisCache redisCache;

    @Resource
    private ISysOrderReminderConfigService reminderConfigService;

    @Resource
    private ObsOrderFaultMapper obsOrderFaultMapper;

    @Resource
    private IObsOrderMakeService makeService;

    @Resource
    private ISysUserTeamService userTeamService;

    @Resource
    private ISysMessageService messageService;

    @Override
    public void centreRepairRemind(String faultType) {
        if (StrUtil.isNotEmpty(faultType)) {
            SysOrderReminderConfigVo configVo = reminderConfigService.getDefaultConfig();
            if (configVo.getCentralizedRepairRemind() != null && configVo.getCentralizedRepairRemind() &&
                    configVo.getRepairMinute() != null && configVo.getRepairTimes() != null) {
                Integer repairMinute = configVo.getRepairMinute();
                int repairTimes = configVo.getRepairTimes();
                LocalDateTime startTime = LocalTimeUtil.addLocalMinutes(LocalDateTime.now(), -repairMinute);
                RepairRemindCountVO countVO = obsOrderFaultMapper.getRepairRemindCount(startTime, faultType);
                if (countVO != null && countVO.getCount() != null) {
                    int count = countVO.getCount();
                    String faultTypeName = countVO.getFaultTypeName() == null ? "" : countVO.getFaultTypeName();
                    String parentFaultType = countVO.getParentFaultTypeName() == null ? "" : countVO.getParentFaultTypeName();
                    if (count >= repairTimes) {
                        String msg = "当前有" + count + "个工单" + repairMinute + "分钟内同时报修【" + parentFaultType + "-" + faultTypeName + "】，请谨慎";
                        sendServiceMsg(msg);
                    }
                }
            }
        }

    }

    /**
     * 发送服务台消息
     *
     * @param msg
     */
    @Override
    public void sendServiceMsg(String msg){
        //获取当前坐席人员
        Map<String, Object> cacheMap = redisCache.getCacheMap(CacheConstants.SEAT_NOW);
        if (cacheMap != null) {
            //当前坐席人员id
            List<Object> userIds = Arrays.asList(cacheMap.values().toArray());
            if (CollUtil.isNotEmpty(userIds)) {
                try {
                    userIds.forEach(userId -> {
                        if (userId != null) {
                            String jsonMsg = JSONObject.toJSONString(new ServerDeskWebSocketVO(msg, SERVICE_MESSAGE.name(), SERVICE_MESSAGE.getCode(), SERVICE_MESSAGE.getMsg()));
                            WebSocketUtils.send(jsonMsg, Long.parseLong(userId.toString()));
                        }
                    });
                } catch (Exception e) {
                    log.error("推送服务台信息异常", e);
                }
            }
        }
    }

    @Override
    public void sendEvaluateRemind(Integer evaluateResult,String orderNum) {
        if (evaluateResult != null) {
            SysOrderReminderConfigVo configVo = reminderConfigService.getDefaultConfig();
            if (configVo.getEvaluateResultRemind() != null && configVo.getEvaluateResultRemind()&&
                    StrUtil.isNotEmpty(configVo.getEvaluateResult())) {
                String evaluateResults= configVo.getEvaluateResult();
                if(evaluateResults.contains(String.valueOf(evaluateResult))&&StrUtil.isNotEmpty(configVo.getEvaluateResultReminder())){
                    String reminder=configVo.getEvaluateResultReminder();
                    EvaluateResultEnum resultEnum=EnumUtil.getBy(EvaluateResultEnum.class,(re->re.getValue()==evaluateResult.intValue()));
                    String msg = "工单号【"+orderNum+"】评价结果为”"+resultEnum.getName()+"“，请知晓";
                    // 发送服务台
                    if(reminder.contains("1")){
                        sendServiceMsg(msg);
                    }
                    // 发送组长
                    if(reminder.contains("2")){
                        //查询工单当前处理人
                        ObsOrderMake make = makeService.lambdaQuery().eq(ObsOrderMake::getOrderNum, orderNum).one();
                        if(make!=null&&make.getMakeUser()!=null){
                            List<Long> teamLeaders=userTeamService.getTeamLeaderByMark(make.getMakeUser());
                            messageService.sendBatchSysMessage(MessageTypeEnum.SYS_ORDER.getValue(),teamLeaders,msg);
                        }
                    }
                }
            }
        }
    }
}
